// 用户发出信息标识isUser，用户发出信息数imgCount
var msgScroll,imgCount=0,isUser=false,_userImg,keyupCount=0;;
var sendIpt = $("#J-SendIpt"),
sendMsgCont = $("#J-SendMsgCont"),
sendBtn = $("#J-SendBtn"),
winH = 0,
topBarH = $("#J-TopBar").height(),
sendMsgH,
myIscroll = null,
isEdit=false,
isNull = false,
tcid = null; 

$(function(){  
	
	iscroll();
	init();
	leftmenu("#leftmenu","#wrap");
	keyboardEvent(); 
	askSendMessage("${welcome}");
	meSendMessage();
	getUserImg();  
	hideKeyboard();
	
	$(window).on("resize", function(){ 
    	countPage();
    	myIscroll.refresh();
    	myIscroll.scrollTo(0,myIscroll.maxScrollY,0);
    	msgIscroll();
	});
});
//初始化信息
function init(){
	$("#MaskBtnCancel").on("tap", function(){
		//$("#GlobalMask").fadeOut(500);
		$("#GlobalMask").hide();
	});
	var tabsTitle = $("#J-TabsTitle").find("li"),
	    tabsContent = $("#J-TabsContent").find(".tabs-content-list");
	tabsTitle.on("tap", function(){
	    var index = tabsTitle.index(this);
	    $(this).addClass("curr").siblings().removeClass("curr");
	    tabsContent.hide().eq(index).show();
	});
	
}
//计算页面高度
function countPage(){
    topBarH = $("#J-TopBar").height();
    winH = $(window).height();
    $("#wrap").height(winH);
    sendMsgH = $("#J-SendMsg").height(); 
    $("#content").height(winH - topBarH - sendMsgH); 
}
//滑动条
function iscroll(){
	countPage();
	myIscroll = new iScroll("content",{bounce:false});
}

function askSendMessage(meMessage){//机器人发送的消息
	$.ajax({
		url: mpsurl + "/mobile/eimNlp/getEimAnswer.do",
		type: "post",
		dataType: "text",
		data: {question:meMessage},
		success:function(data){
			var obj = eval("("+data+")");
			var resultCode = obj.resultCode;
			var resultMessage = obj.resultMessage;
			if(resultCode == "500600"){
				var value = obj.value;
				var $liAsk = $("<li>"+
				                    "<div class=\"ask-msg\">"+
				                        "<figure class=\"ask-msg-photo\"><img src=\"../images/pic.png\"></figure>"+
				                        "<div class=\"ask-msg-main\">"+
				                            "<div class=\"msg-main-cont\">"+
				                                "<p></p>"+
				                            "</div>"+                            
				                            "<i></i>"+
				                        "</div>"+
				                    "</div>"+
				                "</li>");
				//var $liAsk = cut($liAsk,value);
//				isUser=false;// 用户发出信息标识
				showMessage($liAsk,value);
				$("ul.ask-list").append($liAsk);
				setTimeout(function(){
					//iscroll();
					if($("div.ask-module").height()>$("#content").height()){
						myIscroll.refresh();
						myIscroll.scrollToElement($("ul.ask-list").next("p").get(0), 0);
					}
				},100);
			}else{
				if(obj.resultCode=="500702" || obj.resultCode=="500802" || obj.resultCode=="500803"){
					checkLogin(obj.resultCode,"",resultMessage);
				}else{
					if(resultMessage==""||undefined==resultMessage||null==resultMessage||"null"==resultMessage)
						setPromptForInput("系统出错，请联系管理员!");
					else
						setPromptForInput(resultMessage);
				}
			}
		},
		error: function (xhr, textStatus, errorThrown) {
		}
	});
}

function meSendMessage(){  //用户发送的消息
	
	$("#J-SendBtn").on("tap", function(){
		var meMessage = $("#J-SendIpt").get(0).value;
	    if(meMessage.trim() != ""){
//	    	imgCount ++;
			if(meMessage!=""){
				var $liMe = $("<li class=\"me\">"+
					"<div class=\"ask-msg\">"+
					"<figure class=\"ask-msg-photo\"><img src='"+_userImg+"'></figure>"+
					"<div class=\"ask-msg-main\">"+
					"<div class=\"msg-main-cont\">"+
					"<p></p>"+
					"</div>"+                            
					"<i></i>"+
					"</div>"+
					"</div>"+
					"</li>");
//				isUser=true; // 用户发出信息标识
				
				
				
				
				showMessage($liMe,meMessage); 
				$("ul.ask-list").append($liMe);
	
				// 清空输入框数据并重新设置数据框的状态
				$("#J-SendIpt").get(0).value = "";
				$("#J-SendIpt").blur();
				isEdit = false;
				sendMsgCont.addClass("disable-edit");
		        isNull = true; 
		        
				// 发起问题请求ajax
				askSendMessage(meMessage);
				/*
				if($("div.ask-module").height()>$("#content").height()){
					myIscroll.refresh();
					myIscroll.scrollToElement($("ul.ask-list").next("p").get(0), 0);
				}
				*/	
			} 
	    }
	    setTimeout(function(){
	    	//iscroll();
	     	myIscroll.refresh();
	     	myIscroll.scrollTo(0,myIscroll.maxScrollY,0);
//	     	if($("div.ask-module").height()>$("#content").height()){
//				myIscroll.scrollToElement($("ul.ask-list").next("p").get(0), 0);
//			}
	   }, 200);
	});  
}

function showMessage(li,str){  //显示每条信息所有内容
	//聊天记录的显示宽度自适应文字长度
	li.find("div.msg-main-cont").css("width", "auto");
	li.find("div.msg-main-cont").css("max-width", "80%"); 
	
	var length = 180;
	var p = $(li).find("p");
	if(str.length<length){
		p.html(str);
//		if(isUser){
//			getUserImg();
//		}
		return li;
	} 
	var strOmit = str.substr(0, length)+"......";
	p.html(strOmit);
//	p.append("<i>查看详情</i>");
//	p.children("i").css("color","#267ada").css("float","right"); 
	// 04-10 modify by sudeming
	p.append("<p style='text-align: right;'><i style='color: #267ada;'>查看详情</i></p>");
	
	$(li).find("div.msg-main-cont").on("tap", function(){
		$("#J-SendIpt")[0].blur();
		$("#msgContent").html(str); 
		$("#mainContent").hide();
		showMsgBox($("#messageBox"));
		
	});
//	if(isUser){
//		getUserImg();
//	}
}
function getUserImg(){
	var flag = true;
	var imgId = "#userImg"+imgCount;
	if(document.cookie.length > 0){
		var cookieArray = document.cookie.split(";");
		for(var k = 0;k < cookieArray.length;k ++){
			var cookieInfo = cookieArray[k].split("=");
			if(cookieInfo[0] == "imgPath"){
				flag = false;
				if(cookieInfo[1]==""){
					_userImg=mpsurl+"/mobile/photo/photo.png";
//					$(imgId).attr("src",mpsurl+"/mobile/photo/photo.png");
				}else{
					_userImg=mpsurl+"/mobile/createPicture/writePicture.do";
//					$(imgId).attr("src",mpsurl+"/mobile/createPicture/writePicture.do");
				}
			}
		}
	}
	if(flag){
		$.ajax({
			type:"post",
			url:mpsurl+"/mobile/base/selectUserByEmpId.do",
			dateType:"json",
			data:{method:"selectUserByEmpId"},
			success:function(data){
				data = eval("("+data+")");
				if(data.resultCode=="500600"){	
					var userDTO = data.userDTO;
					var imgurl = userDTO.imageUrl;
					if(imgurl==""){
						_userImg=mpsurl+"/mobile/photo/photo.png";
//						$(imgId).attr("src",mpsurl+"/mobile/photo/photo.png");
					}else{
						_userImg=mpsurl+"/mobile/createPicture/writePicture.do";
//						$(imgId).attr("src",mpsurl+"/mobile/createPicture/writePicture.do");
					}
					document.cookie = "imgPath="+escape("ajaxImagePath");
				}else{
					if(data.resultCode=="500702" || data.resultCode=="500802" || data.resultCode=="500803"){
						checkLogin(data.resultCode,"/mobile/index.html","");
					}else{
						setPromptForInput("系统出错，请联系管理员!");
					}
				}
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				setPromptForInput("系统出错，请联系管理员!");
			}
		});
	}
}
function keyboardEvent(){
	$("#J-SendIpt").on("input", function(){
		var sendMsgCont = $("#J-SendMsgCont");
	    if($("div.ask-module").height()>$("#content").height()){
    		countPage();
    		myIscroll.refresh();
			myIscroll.scrollToElement($("ul.ask-list").next("p").get(0), 0);
		}
		 
		if(this.value.trim() == ''){        
			sendMsgCont.addClass("disable-edit");
			isEdit = false;
			if(isNull) return;
	        isNull = true; 
	    }else{
	    	sendMsgCont.removeClass("disable-edit");
	        isNull = false;
	        if(isEdit) return;
	        isEdit = true; 
	    }
	}).on("blur",function(){
		// setTimeout(function(){
//			 if($("div.ask-module").height()>$("#content").height()){
//					myIscroll.scrollToElement($("ul.ask-list").next("p").get(0), 0);
//			 }
			 	//iscroll();
				countPage();
			    myIscroll.refresh();
				myIscroll.scrollTo(0,myIscroll.maxScrollY,0);
		   //}, 200);
	});
}



//添加详细页面滚动
function msgIscroll(){
	var wh = $(window).height()-90; 
	if(msgScroll instanceof iScroll)
		msgScroll.destroy();
	$("#content2").css("height",wh+"px");
	msgScroll = new iScroll("content2");
}
//返回主页面
function returnMain(){
	hideMsgBox($("#messageBox"), function(){
		$("#mainContent").show();
		// 04-10 modify by sudeming
	    
	    	//iscroll();
		countPage();
     	myIscroll.refresh();
     	myIscroll.scrollTo(0,myIscroll.maxScrollY,0);
	   
	});
	
}
//单个信息向上展开效果
function showMsgBox(obj, callback){
	obj.css("-webkit-transform", "translate3d(0px, " + window.innerHeight + "px, 0px);");
	obj.show().animate({
        "-webkit-transform": "translate3d(0px, 0px, 0px);"}
    , 500, "ease-in-out", callback);
	msgIscroll();
}
//单个信息向下隐藏效果
function hideMsgBox(obj, callback) {
	obj.animate({
        "-webkit-transform": "translate3d(0px, " + window.innerHeight + "px, 0px);"}
    , 500, "ease-in-out", function(){
    	obj.hide();
        callback();
    });
}

function hideKeyboard(){
	$("#content").on("tap", function(){ 
		var ua = navigator.userAgent;
		if(ua.indexOf("iPhone")>=0){
		}else{
			window.pa_app.closeKeyboard();
		}
		 
	}); 
}
 